package com.nsoft.remotemedia.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.client.youtube.YouTubeQuery.OrderBy;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.nsoft.remotemedia.objects.VideoItem;

public class U2bUtils {
	private static YouTubeService service;
	
	public static void startUp(){
		service=new YouTubeService(
				Constant.APP_NAME,Constant.YOUTUBE_KEY);
	}
	
	public static List<VideoItem> getFeeds(String searchStr)
						throws Exception {
		List<VideoItem> itemList=new ArrayList<VideoItem>();
		try{
			String actualStr=searchStr.replaceAll(
					Constant.CHR_SPACE,Constant.CHR_PLUS);
			String actualQuery=Constant.u2b.URL_SEARCH.replaceAll(
					Constant.CHR_REPLACE,actualStr);
			YouTubeQuery query=new YouTubeQuery(
								new URL(actualQuery));
			query.setOrderBy(OrderBy.VIEW_COUNT);
			VideoFeed feeds=service.query(query,VideoFeed.class);
			List<VideoEntry> videoList=feeds.getEntries();
			
			VideoItem item;
			YouTubeMediaGroup mediaGroup;
			for (VideoEntry v:videoList){
				item=new VideoItem();
				mediaGroup=v.getMediaGroup();
				if (mediaGroup!=null){
					item.setId(mediaGroup.getVideoId());
					item.setTitle(mediaGroup.getTitle().
								getPlainTextContent());
					item.setAuthor(mediaGroup.getUploader());
					item.setSummary(mediaGroup.getDescription().
								getPlainTextContent());
					item.setImageUrl(mediaGroup.getThumbnails().size()>0?
							mediaGroup.getThumbnails().get(0).getUrl():
								Constant.EMPTY);
					item.setPostTime(new Date(
							mediaGroup.getUploaded().getValue()));
					item.setDuration(mediaGroup.getDuration());
				}
				item.setVideoUrl(v.getLinks().size()>0?
							v.getLinks().get(0).getHref():
								Constant.EMPTY);
				item.setRate(v.getRating()!=null?
						v.getRating().getAverage():
							Constant.u2b.DEFAULT_RATE);
				item.setViewCount(v.getStatistics()!=null?
						v.getStatistics().getViewCount():
							Constant.u2b.DEFAULT_VIEWCOUNT);
				itemList.add(item);
			}
			
			return itemList;
		}catch(Exception e){
			throw e;
		}
	}
	
	public static List<VideoItem> getMostPopularFeeds()
						throws Exception{
		List<VideoItem> itemList=new ArrayList<VideoItem>();
		try{
			YouTubeQuery query=new YouTubeQuery(
						new URL(Constant.u2b.URL_MOST_POPULAR_KR));
			query.setOrderBy(OrderBy.VIEW_COUNT);
			VideoFeed feeds=service.query(query,VideoFeed.class);
			List<VideoEntry> videoList=feeds.getEntries();
			
			VideoItem item;
			YouTubeMediaGroup mediaGroup;
			for (VideoEntry v:videoList){
				item=new VideoItem();
				mediaGroup=v.getMediaGroup();
				if (mediaGroup!=null){
					item.setId(mediaGroup.getVideoId());
					item.setTitle(mediaGroup.getTitle().
								getPlainTextContent());
					item.setAuthor(mediaGroup.getUploader());
					item.setSummary(mediaGroup.getDescription().
								getPlainTextContent());
					item.setImageUrl(mediaGroup.getThumbnails().size()>0?
							mediaGroup.getThumbnails().get(0).getUrl():
								Constant.EMPTY);
					item.setPostTime(new Date(
							mediaGroup.getUploaded().getValue()));
					item.setDuration(mediaGroup.getDuration());
				}
				item.setVideoUrl(v.getLinks().size()>0?
							v.getLinks().get(0).getHref():
								Constant.EMPTY);
				item.setRate(v.getRating()!=null?
						v.getRating().getAverage():
							Constant.u2b.DEFAULT_RATE);
				item.setViewCount(v.getStatistics()!=null?
						v.getStatistics().getViewCount():
							Constant.u2b.DEFAULT_VIEWCOUNT);
				itemList.add(item);
			}
			return itemList;
		}catch(Exception e){
			throw e;
		}
	}
	
	public static Bitmap getBitmapFromUrl(
					String bmpUrl) throws Exception{
		try {
	        URL url=new URL(bmpUrl);
	        HttpURLConnection connection=
	        		(HttpURLConnection)url.openConnection();
	        connection.setDoInput(true);
	        connection.connect();
	        InputStream input=connection.getInputStream();
	        Bitmap myBitmap=BitmapFactory.decodeStream(input);
	        return myBitmap;
	    }catch(IOException e){
	    	throw e;
	    }
	}
	
	public static String getDuration(long dur){
		int hour=0,min=0,sec=0;
		hour=(int)(dur/3600);
		min=(int)((dur%3600)/60);
		sec=(int)(dur-(hour*3600+min*60));
		if (hour==0){
			return String.format("%02d",min)+
				Constant.CHR_COLON+
				String.format("%02d",sec);
		}else{
			return String.format("%02d",hour)+
					Constant.CHR_COLON+
					String.format("%02d",min)+
					Constant.CHR_COLON+
					String.format("%02d",sec);
		}
	}
	
}
